import argon2 from 'argon2';
import User from '../models/user.js';
import redisClient from '../utils/redis.js';
import { decryptData } from '../utils/crypto.js';
import sequelize from '../config/db.js'; // 根据实际路径导入
const transaction = await sequelize.transaction();
// 注册接口
export const register = async (ctx) => {
  const { encryptedData, accessToken } = ctx.request.body;
  let data = await decryptData(encryptedData);
  const { email, password, username, emailCaptcha, imgCode } = data
  const storedCode = await redisClient.get(`verification:${email}`);
  // 字段完整性校验
  if (!email || !password || !username || !emailCaptcha || !imgCode) {
    ctx.body = { code: 400, message: '所有字段均为必填项' }
    return
  }
  const isValid = await redisClient.exists(`access:${accessToken}`);
  if (!isValid) {
    ctx.body = {
      code: 403,
      message: "请获取邮箱验证码"
    }
    return;
  }
  // 验证码校验
  if (emailCaptcha !== storedCode) {
    ctx.body = {
      code: 403,
      message: "邮箱验证码错误或已过期"
    }
    return
  }


  // 3. 后端二次加密

  const hashedPassword = await argon2.hash(password, {
    type: argon2.argon2id, // 使用 argon2id 算法
    timeCost: 3,           // 时间成本（默认 3）
    memoryCost: 4096,      // 内存成本（默认 4096 KB）
    parallelism: 1,        // 并行度（默认 1）
  });

  const existingUser = await User.findOne({ where: { email }, transaction });
  console.log('%c [ existingUser ]-46', 'font-size:13px; background:pink; color:#bf2c9f;', existingUser)
  if (existingUser) {
    ctx.body = {
      code: 403,
      message: "邮箱已存在"
    }
    return
  }
  // 4. 存储用户
  await User.create({
    email: email,
    username: username,
    password: hashedPassword
  });
  ctx.body = {
    code: 200,
    message: "注册成功"
  }
  // 清理验证码缓存
  await redisClient.del(`verification:${email}`);
};
